package command

import (
	"fmt"
	"time"

	"github.com/google/uuid"
	agentv1beta1 "gopkg.openfuyao.cn/bkeagent/api/v1beta1"
	confv1beta1 "gopkg.openfuyao.cn/bkecommon/cluster/api/v1beta1"
	bkenode "gopkg.openfuyao.cn/bkecommon/cluster/node"
)

type Collect struct {
	BaseCommand

	Node                *confv1beta1.Node
	EtcdCertificatesDir string
	K8sCertificatesDir  string
}

func (c *Collect) Validate() error {
	if c.EtcdCertificatesDir == "" {
		return fmt.Errorf("etcdCertificatesDir is empty")
	}
	if c.K8sCertificatesDir == "" {
		return fmt.Errorf("k8sCertificatesDir is empty")
	}
	if c.Node == nil {
		return fmt.Errorf("node is empty")
	}
	if c.ClusterName == "" {
		return fmt.Errorf("cluster name is empty")
	}
	return c.BaseCommand.validate()
}

func (c *Collect) New() error {
	if err := c.Validate(); err != nil {
		return err
	}
	clusterName := fmt.Sprintf("clusterName=%s", c.ClusterName)
	nameSpace := fmt.Sprintf("namespace=%s", c.NameSpace)
	k8sCertDir := fmt.Sprintf("k8sCertDir=%s", c.K8sCertificatesDir)
	etcdCertDir := fmt.Sprintf("etcdCertDir=%s", c.EtcdCertificatesDir)
	commandName := fmt.Sprintf("%s-%s-%d", CollectCertCommandNamePrefix, c.ClusterName, time.Now().Unix())
	commandSpec := GenerateDefaultCommandSpec()
	commandSpec.Commands = []agentv1beta1.ExecCommand{
		{
			ID: uuid.New().String(),
			Command: []string{
				"Collect",
				clusterName,
				nameSpace,
				k8sCertDir,
				etcdCertDir,
			},
			Type: agentv1beta1.CommandBuiltIn,
		},
	}
	nodes := bkenode.Nodes{*c.Node}
	commandSpec.NodeSelector = getNodeSelector(nodes)
	return c.newCommand(commandName, BKEClusterLabel, commandSpec)
}

func (c *Collect) Wait() (error, []string, []string) {
	err, _, successNodes, failedNodes := c.waitCommandComplete()
	return err, successNodes, failedNodes
}
